const fs = require('fs')
const { isDev } = require('../utils/index')
const config = require('../config/default.json')
const log = require('../utils/logger')

const configPath = './config/config.json'


// 初始化配置文件
const initConfig = () => {
  if (isDev) {
    return config
  } else {
    // 检测文件夹
    try {
      const fdata = fs.readFileSync(configPath, { encoding: 'utf-8' })
      return JSON.parse(fdata)
    } catch (e) {
      if (e.toString().indexOf('JSON') !== -1) {
        log.error('The configuration file format is incorrect, and will exit the process !')
        process.exit() // 配置文件格式错误，退出进程
      }
      try {
        fs.readdirSync('./config')
      } catch (e) {
        fs.mkdirSync('./config')
      }
      fs.writeFileSync(configPath, JSON.stringify(config, '', 2))
      return config
    }
  }
}

// 获取配置文件信息
const getConfig = () => {
  if (isDev) return config
  return JSON.parse(fs.readFileSync(configPath))
}

// 获取配置文件里面的值
const getKey = (key) => {
  let config = getConfig()
  return config[key]
}

// 设置配置信息
const setKey = (key, val) => {
  if (isDev) return
  let config = getConfig()
  config[key] = val
  fs.writeFileSync(configPath, JSON.stringify(config, '', 2))
}


module.exports = { initConfig, getKey, setKey }